<template>
  <div class="md:flex h-full">
    <div class="w-1/6 h-full" style="border-bottom: 1px solid #e0e0e0; border-right: 1px solid #e0e0e0">
      <Divider orientation="center"><span style="font-weight: bolder">资源列表</span></Divider>
      <span style="border: 1px solid rgba(0, 30, 255, 0.72); margin-top: -13px; height: 31.5px">
        <Select v-model:value="appId" placeholder="请选择应用" style="margin: -2px; width: 250px">
          <SelectOption v-for="option in appSelectList" v-bind:key="option.id" :value="option.id"
            >{{ option.name }}
          </SelectOption>
        </Select>
      </span>
      <Divider orientation="right" v-if="appId !== undefined" style="border-width: 0; margin-bottom: 2px">
        <span v-per="'addRootNode'">
          <Button type="primary" @click="addResourceHandler('', '', 'new root')">新增根节点</Button></span
        >
      </Divider>
      <Tree
        :showLine="false"
        :fieldNames="{ key: 'id', title: 'title', children: 'children' }"
        style="font-weight: bolder; text-align: right"
        :tree-data="treeData"
        :autoExpandParent="false"
        @select="onSelect"
      >
        <template #title="{ title, type, id }">
          <Dropdown :trigger="['contextmenu']">
            <span>
              <Tag color="pink" v-if="type === 'MENU'">{{ type }}</Tag>
              <Tag color="blue" v-if="type === 'ELEMENT'">{{ type }}</Tag>
              {{ title }}
            </span>
            <template #overlay>
              <Menu>
                <MenuItem
                  key="1"
                  v-if="type === 'MENU' && checkPowerByName('addResource')"
                  @click="addResourceHandler(title, id, 'new child')"
                >
                  <MenuUnfoldOutlined />
                  新增资源
                </MenuItem>
                <MenuItem
                  key="1"
                  v-if="type === 'MENU' && checkPowerByName('updateResource')"
                  @click="addResourceHandler(title, id, 'edit')"
                >
                  <EditOutlined />
                  编辑信息
                </MenuItem>
                <MenuItem key="1" v-if="type === 'MENU' && checkPowerByName('deleteResource')">
                  <Popconfirm cancel-text="取消" ok-text="确认" title="确定要删除吗?" @confirm="onDelete(id)">
                    <DeleteOutlined />
                    删除
                  </Popconfirm>
                </MenuItem>
                <MenuItem
                  key="1"
                  v-if="type === 'ELEMENT' && checkPowerByName('updateResource')"
                  @click="addResourceHandler(title, id, 'edit')"
                >
                  <EditOutlined />
                  编辑信息
                </MenuItem>
                <MenuItem key="1" v-if="type === 'ELEMENT' && checkPowerByName('deleteResource')">
                  <Popconfirm cancel-text="取消" ok-text="确认" title="确定要删除吗?" @confirm="onDelete(id)">
                    <DeleteOutlined />
                    删除
                  </Popconfirm>
                </MenuItem>
              </Menu>
            </template>
          </Dropdown>
        </template>
      </Tree>
    </div>
    <div class="w-7/8 h-full" ref="drawerContainer">
      <div
        :style="{
          overflow: 'hidden',
          position: 'relative',
          border: '1px solid #ebedf0',
          borderRadius: '2px',
          padding: '48px',
          textAlign: 'center',
          background: '#fafafa',
          width: '100%',
        }"
        class="w-7/8 h-full"
      >
        <InfoDrawer ref="drawerRef" @success="successHandler"></InfoDrawer>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  Tree,
  TreeProps,
  Dropdown,
  Menu,
  MenuItem,
  Tag,
  Button,
  Popconfirm,
  Divider,
  Select,
  SelectOption,
} from 'ant-design-vue';
import { nextTick, onMounted, ref, watch } from 'vue';
import InfoDrawer from '/@/views/system-mgmt/app-resource-mgmt/InfoDrawer.vue';
import { EditOutlined, MenuUnfoldOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { deleteResource } from '/@/api/system-mgmt/app-resource-mgmt/resource';
import { useTreeData } from '/@/views/system-mgmt/app-resource-mgmt/editData';
import { getAppsList, getMenuAndElementResourceTree } from '/@/api/system-mgmt/instance-mgmt/instance';
import { SaaSMenuListItem } from '/@/api/authority-mgmt/model/roleModel';
import { checkPowerByName } from '/@/utils/permission';

const appId = ref();
const appSelectList = ref([]);
const drawerRef = ref();
const treeData = ref<TreeProps['treeData']>([]);
const treeNode = ref();
const { setData } = useTreeData();

onMounted(async () => {
  appSelectList.value = await getAppsList();
});

watch(
  () => appId.value,
  async () => {
    treeData.value = await getMenuAndElementResourceTree({ appId: appId.value });
    if (drawerRef.value.visible) {
      drawerRef.value.onClose();
    }

    if (treeData.value.length !== 0) {
      await nextTick(() => {
        setTimeout(async () => {
          let tempNode: SaaSMenuListItem = {};
          tempNode.node = treeData.value[0];
          await drawerRef.value.openDrawer(treeData.value[0].title, tempNode, 'info', appId.value);
        }, '450');
      });
    }
  }
);

const onSelect: TreeProps['onSelect'] = async (selectedKeys, info) => {
  if (drawerRef.value.visible) {
    drawerRef.value.onClose();
  }
  nextTick(() => {
    setTimeout(() => {
      drawerRef.value.openDrawer(info.node.title, info, 'info', appId.value);
    }, '450');
  });
};

const findNode = (tree: any, key: string) => {
  if (tree.id === key) {
    setData(tree);
  }
  if (tree.children !== undefined) {
    tree.children?.forEach((item) => {
      findNode(item, key);
    });
  }
};

const addResourceHandler = (info, id, type) => {
  if (drawerRef.value.visible) {
    drawerRef.value.onClose();
  }
  nextTick(() => {
    setTimeout(async () => {
      if (type === 'edit') {
        await treeData.value.forEach((item) => {
          findNode(item, id);
        });
        await drawerRef.value.openDrawer(info, treeNode.value, type, appId.value);
      } else {
        drawerRef.value.openDrawer(info, id, type, appId.value);
      }
    }, '450');
  });
};
const onDelete = async (id: string) => {
  await deleteResource({ id: id });
  if (drawerRef.value.visible) {
    drawerRef.value.onClose();
  }
  treeData.value = await getMenuAndElementResourceTree({ appId: appId.value });
};

const successHandler = async () => {
  treeData.value = await getMenuAndElementResourceTree({ appId: appId.value });
};
</script>

<style lang="less">
.drawer-wrapper {
  position: absolute;
  overflow: hidden;
}
</style>
